package cn.lcc.utils.controller;

import cn.lcc.utils.commom.Resp;
import cn.lcc.utils.service.BaseFluxService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

import java.time.Duration;

@Slf4j
@RestController
public class DemoController {

    @Autowired
    private BaseFluxService deviceService;

    // 监听
    @GetMapping("gen")
    public Resp getLog() {
        String str = "asdafsasf";
        deviceService.publishMsg();
        return Resp.success();
    }
    private static final Mono TIMEOUT_RESULT = Mono.just(Resp.fail("消息发送成功,客户端响应超时（至于设备为什么不应答，请联系设备厂商",4001 ));
    private static final Mono SENDFAIL_RESULT = Mono.just(Resp.fail("消息发送失败",4001 ));

    // 监听
    @GetMapping("req")
    public Mono<Resp>  getLogs() {
        Mono<String> receive = deviceService.generateData2();
        Mono<String> s = Mono.create(sink -> {
            sink.success("发送成功");
        }).then(receive).doFinally(signal -> deviceService.unsubscribe());
        return s.map(message -> Resp.success(message))
                .timeout(Duration.ofSeconds(10), TIMEOUT_RESULT)
                .onErrorResume(e -> {
                    log.warn("消息发送失败", e);
                    return SENDFAIL_RESULT;
                });
    }


}
